package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
//@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增账户记录
     *
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initUserAccount(Long userId) {
        //1.根据用户ID查询账户记录（数据表中user_id有唯一索引）
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        Long count = userAccountMapper.selectCount(queryWrapper);
        if (count > 0) {
            //2.存在则直接返回，不处理
            return;
        }
        //3.不存在则构建账户对象新增
        UserAccount userAccount = new UserAccount();
        //用户ID
        userAccount.setUserId(userId);
        //总金额
        userAccount.setTotalAmount(new BigDecimal("1000"));
        //锁定、冻结金额
        userAccount.setLockAmount(new BigDecimal("0"));
        //可用金额
        userAccount.setAvailableAmount(new BigDecimal("1000"));
        //总收入=充值，收益
        userAccount.setTotalIncomeAmount(new BigDecimal("0"));
        //总之处
        userAccount.setTotalPayAmount(new BigDecimal("0"));
        userAccountMapper.insert(userAccount);
    }

    /**
     * 获取当前登录用户账户可用余额
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        //1.根据用户ID查询账户记录
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);
        Assert.notNull(userAccount, "账户为空！");
        //2.获取账户可用金额
        return userAccount.getAvailableAmount();
    }

    /**
     * 扣减账户余额
     *
     * @param userId
     * @param accountDeductVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NEVER)
    public void checkAndDeduct(Long userId, AccountLockVo accountDeductVo) {
        //1.对账户扣减操作进行幂等性处理-避免同一个订单多次进行扣减
        String key = "account:deduct:" + accountDeductVo.getOrderNo();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, accountDeductVo.getOrderNo(), 1, TimeUnit.HOURS);
        if (flag) {
            try {
                //2.扣减账户余额
                int count = userAccountMapper.checkAndDeduct(userId, accountDeductVo.getAmount());
                if (count == 0) {
                    throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
                }
                //3.新增账户变动日志
                saveUserAccountDetail(userId, "消费："+accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
            } catch (Exception e) {
                //如果扣减余额或者新增账户异常：全局事务回回滚，再次进行余额付款 固将锁定Key删除
                redisTemplate.delete(key);
                throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
            }
        }
    }

    /**
     * 新增账户变动历史记录
     *
     * @param userId    用户ID
     * @param title     事由
     * @param tradeType 类型
     * @param amount    金额
     * @param orderNo   订单编号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 新增余额
     * @param userId
     * @param rechargeAmount
     */
    @Override
    public void add(Long userId, BigDecimal rechargeAmount) {
        int count = userAccountMapper.add(userId, rechargeAmount);
        if(count==0){
            throw new GuiguException(212, "账户充值失败");
        }
    }


    /**
     * 分页获取用户充值记录"
     *
     * @return
     */
    @Override
    public void getUserRechargePage(Long userId, Page<UserAccountDetail> pageInfo) {
        userAccountDetailMapper.getUserRechargePage(pageInfo, userId, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT);
    }
    /**
     * 分页获取用户消费记录
     *
     * @return
     */
    @Override
    public void getUserUserConsumePage(Long userId, Page<UserAccountDetail> pageInfo) {
        userAccountDetailMapper.getUserRechargePage(pageInfo, userId, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS);
    }
}
